package pl.rzarajczyk.breaktime;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pl.rzarajczyk.breaktime.utils.Utils;

/**
 *
 * @author rafalz
 */
public class ApplicationFramework {
    
    private static ApplicationFramework instance;
    public static ApplicationFramework getInstance() {
        if ( instance == null ) {
            instance = new ApplicationFramework();
        }
        return instance;
    }
    private ApplicationFramework() {
    }
    
    
    
    private ClassPathXmlApplicationContext context;
    private Log log = LogFactory.getLog(Main.class);


    public void start() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, AWTException, IOException, InterruptedException {
        log.info("Starting the application");
        String lookAndFeelName = UIManager.getSystemLookAndFeelClassName();
        UIManager.setLookAndFeel(lookAndFeelName);
        log.info("Look-and-Feel set to: " + lookAndFeelName);
        log.info("Private dir set to: " + Utils.getPrivateDir().getAbsolutePath());
        log.info("Temp dir set to: " + Utils.getTempDir().getAbsolutePath());
               
        String [] springXmlFiles = new String [] {"spring/context.xml"};
        context = new ClassPathXmlApplicationContext(springXmlFiles);
        Menu menu = (Menu) context.getBean("menu");
        tray(menu);
        log.info("Application started!");
    }
    
    public void stop() {
        context.close();
        System.exit(0);
    }
    
    private void tray(final Menu menu) throws AWTException, IOException, InterruptedException {
        int count = BreakTimeSettings.TRAY_INITIALIZATION_COUNT;
        while ( !SystemTray.isSupported() && count > 0 ) {
            log.warn("SystemTray is not available. Retrying in " + BreakTimeSettings.TRAY_INITIALIZATION_INTERVAL + " ms (" + count + ")");
            Thread.sleep(BreakTimeSettings.TRAY_INITIALIZATION_INTERVAL);
            count--;
        }
        
        if ( ! SystemTray.isSupported() )
            throw new UnsupportedOperationException("SystemTray is not available in your system");

        URL rsrcUrl = Main.class.getResource("/tray-icon.png");
        Image image = ImageIO.read(rsrcUrl);

        TrayIcon tray = new TrayIcon(image, "Break time!", null);
        tray.setToolTip("Break time!");
        tray.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                menu.setLocation( e.getLocationOnScreen() );
                if ( e.getButton() == MouseEvent.BUTTON1 ) {
                    menu.invokeDefaultAction(e);
                } else  if ( e.getButton() == MouseEvent.BUTTON3 ) {
                    menu.setLocation(e.getX(), e.getY());
                    menu.setVisible(true);
                }
            }


        });
        
        SystemTray.getSystemTray().add(tray);
    }
    
}
